package com.tang.provider;

import com.tang.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by tangyifei on 2018/7/6.
 */
@Api(value = "micro-service-core-nosql-redis", tags = {"micro-service-core-nosql-redis"})
@Controller
public class RedisProvider {

    private static final Logger logger = LogManager.getLogger(RedisProvider.class);

    @Resource
    private RedisUtil redisUtil;

    /**
     * 放到缓存中保存
     *
     * @param key   相关的键
     * @param value 相关的值
     * @throws Exception
     */
    @ApiOperation(value = "放到缓存中保存", httpMethod = "POST", notes = "放到缓存中保存")
    @PostMapping("/redis/{key}")
    public ResponseEntity<?> set(
            @PathVariable("key") @ApiParam(required = true, name = "key", value = "相关的键") String key,
            @RequestBody @ApiParam(required = true, name = "value", value = "相关的值") Map<String, Object> value)
            throws Exception {
        redisUtil.set(key, value);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取缓存中的值
     *
     * @param key 相关的键
     * @throws Exception
     */
    @ApiOperation(value = "获取缓存中的值", httpMethod = "GET", notes = "获取缓存中的值")
    @GetMapping("/redis/{key}")
    public ResponseEntity<?> get(
            @PathVariable("key") @ApiParam(required = true, name = "key", value = "相关的键") String key)
            throws Exception {
        return new ResponseEntity<>(redisUtil.get(key), HttpStatus.OK);
    }

    /**
     * 从缓存中删除某个key相关的值(数组形式字符串中必须使用逗号分隔)
     *
     * @param key     相关的键
     * @param pattern 相关的键的模式
     * @throws Exception
     */
    @ApiOperation(value = "从缓存中删除某个key相关的值(数组形式字符串中必须使用逗号分隔)", httpMethod = "DELETE", notes = "从缓存中删除某个key相关的值(数组形式字符串中必须使用逗号分隔)")
    @DeleteMapping("/redis/{key}")
    public ResponseEntity<?> deleteByPattern(
            @PathVariable("key") @ApiParam(required = true, name = "key", value = "相关的键") String key,
            @RequestParam(value = "pattern", required = false) @ApiParam(required = false, name = "pattern", value = "相关的键的模式") String pattern)
            throws Exception {
        if (!StringUtils.isEmpty(pattern)) {
            redisUtil.deleteByPattern(pattern);
        } else {
            redisUtil.del(key.split(","));
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
